package com.yangran.controller;

import com.alibaba.fastjson.JSONObject;
import com.yangran.strategy.factory.MessageHandlerStrategy;
import com.yangran.vo.MsgVo;
import com.yangran.vo.MyFacts;
import org.jeasy.rules.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lishan
 * @date 2023/3/5
 */
@RequestMapping("/kafka")
@RestController
public class RuleTestController {

    @Autowired
    private Rules rules;

    @Autowired
    private RulesEngine rulesEngine;

    //**************************************   规则引擎测试生产者  ***************************//

    /**
     * 规则引擎测试生产者
     *
     * @param message
     * @return
     */
    @GetMapping("/send/{message}/{version}")
    public String send(@PathVariable String message, @PathVariable Integer version) {
        MsgVo msgVo = new MsgVo(message, version);

        System.out.println("规则引擎测试消费者收到消息:" + JSONObject.toJSONString(msgVo));

        // 3、定义事实（也就是执行节点的上下文入参）
        Fact<MsgVo> fact = new Fact("msg", msgVo);
        MyFacts facts = new MyFacts();
        facts.add(fact);

        // 4、 触发执行
        rulesEngine.fire(rules, facts);

        //5、获取handler并遍历执行
        for (MessageHandlerStrategy messageHandlerStrategy : facts.getHandlerList()) {
            String result = (String)messageHandlerStrategy.execute(facts);
            System.out.println(result);
        }
        System.out.println("消费正常：" + JSONObject.toJSONString(msgVo));

        return "success";
    }


    /**
     * 测试每次调用的容器中的对象是否多例的
     *
     * @return
     */
    @GetMapping("/prototype")
    public String testSingle() {
        for (Rule rule : rules) {
            System.out.println(System.identityHashCode(rule));
        }
        return "success";
    }

}




